<template>
  <div class="border border-solid border-gray-100 h-full min-h-80">
    <Toolbar :editor="editorRef" :default-config="toolbarConfig" mode="default" />
    <Editor v-model="modelValue" class="overflow-y-hidden mt-0.5" :default-config="editorConfig" mode="default"
      @onCreated="handleCreated" @onChange="内容变化" ref="ed" />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
const basePath = import.meta.env.VITE_BASE_API
import { onBeforeUnmount, ref, shallowRef, watch, reactive } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import { useUserStore } from '@/stores/use_user_store'
import { ElMessage } from 'element-plus'
import { 予图片路径, 图片元素加后台, 图片元素减后台 } from '@/utils'

const userStore = useUserStore()
const 展示内容 = ref()
const emits = defineEmits(['change'])

const 内容变化 = (editor) => {
  // console.log(`内容变化 ing👇`)
  // emits('change', editor)
  // const regex = new RegExp(`(?<=<img [^>]*src=['"])(${basePath})+(?=[^'"]+[^>]*>)`, 'g');
  // modelValue.value = 展示内容.value.replace(regex, '')
  // modelValue.value = 图片元素减后台(展示内容.value, basePath)
}

const modelValue = defineModel()

const editorRef = shallowRef()

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请开始描述吧……',
  MENU_CONF: {},
}

editorConfig.MENU_CONF['uploadImage'] = {
  fieldName: 'file',
  server: basePath + '/fileUploadAndDownload/upload?noSave=1',
  customInsert(res, insertFn) {
    if (res.code === 0) {
      const 源url = res.data.file.url
      const url = 予图片路径(源url)
      // console.log(`urlPath 👉`,urlPath)
      insertFn(url, res.data.file.name)
      console.log(`自定义插入图片 ing👇`)
      return
    }
    ElMessage.error(res.msg)
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor
  // 展示内容.value = modelValue.value.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
  //   console.log('capture: ', capture);
  //   const 新 = 予图片路径(capture)
  //   // console.log('新: ', 新);
  //   return match.replace(capture, 新);
  // });
  // 展示内容.value = 图片元素加后台(modelValue.value, basePath)
}

</script>

<style scoped lang="scss">
.kk {
  min-height: 300px;
}
</style>
